<?php
namespace Plugin\Controller;
use Think\Controller;
/**
 * Appframe项目公共Action
 */
class UploadController extends Controller 
{
    protected $imageObj;
    public function _initialize()
    {
      $this->imageObj = D("Image");
    }
    public function addImage($src="null",$alt="null")
    {
        $data['src']=$src;
        $data['alt']=$alt;
        $data['createtime']=time();
        $addResult =  $this->imageObj->add($data);//返回id
        return $addResult;
    }
    public function upload()
    {
      $verifyToken = md5('unique_salt' . $_POST['timestamp']);

      if (!empty($_FILES) && $_POST['token'] == $verifyToken) 
      {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     '/upload/'; // 设置附件上传（子）目录
        $upload->callback = true;
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
          $fileObj=$info['Filedata'];
          $src=$fileObj['savepath'].$fileObj['savename'];
          $alt=$fileObj['name'];
          $imageId = $this->addImage($src,$alt);
          if ($imageId) 
          {
             $arr = array("status"=>'1',"imageId"=>$imageId,"imageSrc"=>$src,"imageAlt"=>$alt);   
          }else
          {
             $arr = array("status"=>'0',"message"=>'上传成功，但是保存数据出错');
          }
         
          $json_str = json_encode($arr);
          echo $json_str;
        }
      }  
    }
}    

?>
